<template>
  <div class="app-container">
    <!-- 商品信息 -->
    <template v-if="!loading">
      <p class="pageTitle">Edit Product</p>
      <el-form
        ref="productForm"
        :model="formData"
        :rules="formData.rules"
        :hide-required-asterisk="true"
        label-position="top"
        style="margin-bottom:45px;overflow:hidden;padding:1px;"
      >
        <!-- 选择店铺 -->
        <div class="myCard">
          <el-form-item
            class="storeItem"
            prop="storeId"
            label="Choose Store"
            position="left"
          >
            <el-select
              v-model="storeId"
              placeholder="Choose Store"
              @change="chosedStore"
            >
              <el-option
                v-for="item in storeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <template slot="empty">
                <div class="noDataTip">
                  There are no shops yet.&nbsp;<el-button
                    type="text"
                    @click="goStorePage"
                  >Add</el-button>
                </div>
              </template>
            </el-select>
          </el-form-item>
        </div>
        <div :class="['productInfo', !storeId ? 'waiting' : '']">
          <div class="infoLeft">
            <div class="myCard">
              <el-form-item prop="name" label="Title">
                <el-input v-model="formData.name" placeholder="Product title" />
              </el-form-item>
              <el-form-item label="Description">
                <UE
                  :id="ue"
                  ref="ue"
                  :attribute="{ readonly: true }"
                  :default-msg="defaultMsg"
                />
              </el-form-item>
            </div>
            <div class="myCard">
              <el-form-item id="Images" label="Images">
                <img
                  v-for="(item, index) in images"
                  :key="index"
                  :src="
                    item.uri.indexOf('http') === 0
                      ? item.uri
                      : imgPrefix + item.uri + imgSuffix
                  "
                  class="productImg"
                  :style="
                    index === 0
                      ? 'width:100px;height:100px;margin-right: 10px;'
                      : 'margin-right: 10px;'
                  "
                  @click="
                    toProview(
                      item.uri.indexOf('http') === 0
                        ? item.uri
                        : imgPrefix + item.uri
                    )
                  "
                >
              </el-form-item>
            </div>
            <!-- 单一 -->
            <template v-if="formData.type === 0">
              <div class="myCard">
                <p class="myCardTitle">Pricing</p>
                <el-row :gutter="20">
                  <el-col :span="4">
                    <el-form-item prop="salePrice" label="Sale Price">
                      <el-input v-model="formData.salePrice" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="regularPrice" label="Regular Price">
                      <el-input v-model="formData.regularPrice" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="taxStatus" label="Tax status">
                      <el-select v-model="formData.taxStatus">
                        <el-option label="None" :value="0" />
                        <el-option label="Taxable" :value="1" />
                        <el-option label="Shipping only" :value="2" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="taxClass" label="Tax class">
                      <el-select v-model="formData.taxClass">
                        <el-option label="Standard" value="Standard" />
                        <el-option label="Reduced rate" value="Reduced rate" />
                        <el-option label="Zero rate" value="Zero rate" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <div class="myCard">
                <p class="myCardTitle">Inventory</p>
                <el-row :gutter="20">
                  <el-col :span="4">
                    <el-form-item prop="sku" label="SKU">
                      <el-input
                        v-model="formData.sku"
                        placeholder="SKU"
                        @input="changeVariantSku"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item prop="barcode" label="Barcode">
                      <el-input
                        v-model="formData.barcode"
                        placeholder="Barcode"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="Track quantity">
                      <el-checkbox
                        v-model="formData.isManageInventory"
                        :true-label="1"
                        :false-label="0"
                        @change="(val) => toggleCheck(val, 'isManageInventory')"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item
                      v-if="formData.isManageInventory === 0"
                      label="Stock status"
                    >
                      <el-select v-model="formData.inventoryStatus">
                        <el-option label="In stock" :value="0" />
                        <el-option label="Out of stock" :value="1" />
                        <el-option label="On backOrder" :value="2" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <template v-if="formData.isManageInventory">
                    <el-col :span="4">
                      <el-form-item
                        prop="inventoryQuantity"
                        label="Inventory quantity"
                      >
                        <el-input
                          v-model.number="formData.inventoryQuantity"
                          placeholder="inventoryQuantity"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item label="Allow backorders">
                        <el-checkbox
                          v-model="formData.allowBackorders"
                          :true-label="1"
                          :false-label="0"
                          @change="(val) => toggleCheck(val, 'allowBackorders')"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item
                        v-if="formData.allowBackorders"
                        prop="lowInventoryThreshold"
                        label="Low inventory threshold"
                      >
                        <el-input
                          v-model.number="formData.lowInventoryThreshold"
                          placeholder="lowInventoryThreshold"
                        />
                      </el-form-item>
                    </el-col>
                  </template>
                </el-row>
              </div>
              <div class="myCard">
                <p class="myCardTitle">Shipping</p>
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item prop="isVirtual">
                      <el-checkbox
                        v-model="formData.isVirtual"
                        :true-label="1"
                        :false-label="0"
                        @change="(val) => toggleCheck(val, 'isVirtual')"
                      >Is Virtual</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <template v-if="formData.isVirtual === 0">
                  <el-row :gutter="20">
                    <el-col :span="4">
                      <el-form-item prop="weight" label="Weight">
                        <el-input
                          v-model="formData.weight"
                          placeholder="weight"
                        />
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="4">
                      <el-form-item prop="isDimensions" label="Is Dimensions">
                        <el-checkbox
                          v-model="formData.isDimensions"
                          :true-label="1"
                          :false-label="0"
                        >Is Dimensions</el-checkbox>
                      </el-form-item>
                    </el-col> -->
                    <el-col :span="9">
                      <el-form-item label="Dimensions">
                        <el-row
                          class="inputs"
                          type="flex"
                          justify="space-between"
                          :gutter="20"
                        >
                          <el-col :span="8">
                            <el-form-item prop="length">
                              <el-input
                                v-model="formData.length"
                                placeholder="Length"
                              />
                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item prop="width">
                              <el-input
                                v-model="formData.width"
                                placeholder="Width"
                              />
                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item prop="height">
                              <el-input
                                v-model="formData.height"
                                placeholder="Height"
                              />
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        prop="shippingClassId"
                        label="Shipping class"
                      >
                        <el-select v-model="formData.shippingClassId">
                          <el-option label="No shipping class" :value="0" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
              </div>
            </template>
            <div v-if="formData.type === 1" class="myCard">
              <p class="myCardTitle">
                <span>SKU</span>
              </p>
              <el-row>
                <el-col :span="6">
                  <el-input
                    v-model="formData.sku"
                    placeholder="SKU"
                    @input="changeVariantSku"
                  />
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="infoRight">
            <div class="myCard">
              <p class="myCardTitle">Online Store</p>
              <el-form-item label="Publish Time">
                <el-date-picker
                  v-model="formData.publishTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="timeChange"
                />
              </el-form-item>
            </div>
            <div class="myCard">
              <el-form-item prop="productCategoryIds">
                <div slot="label" class="customLabel">
                  <span class="customLabelTitle">Category</span>
                  <el-button
                    type="text"
                    @click="getClick($event, 'category')"
                  >view all</el-button>
                </div>
                <el-cascader
                  v-model="formData.productCategoryIds"
                  :options="categoryOptions"
                  :show-all-levels="false"
                  :props="categoryProp"
                  @visible-change="productCategoryList"
                />
              </el-form-item>
            </div>
            <div class="myCard">
              <el-form-item prop="productTagIds">
                <div slot="label" class="customLabel">
                  <span class="customLabelTitle">Tags</span>
                  <el-button
                    type="text"
                    @click="getClick($event, 'tag')"
                  >view all</el-button>
                </div>
                <el-select
                  v-model="formData.productTagIds"
                  filterable
                  multiple
                  allow-create
                  placeholder="select/add tags"
                  @change="productTagAdd"
                  @visible-change="productTagList"
                >
                  <el-option
                    v-for="item in tagOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="myCard">
              <el-form-item prop="vendorId">
                <div slot="label" class="customLabel">
                  <span class="customLabelTitle">Vendor</span>
                  <el-button
                    type="text"
                    @click="getClick($event, 'vendor')"
                  >view all</el-button>
                </div>
                <el-select
                  v-model="formData.vendorId"
                  filterable
                  allow-create
                  placeholder="select/add vendor"
                  @change="vendorAdd"
                  @visible-change="vendorList"
                >
                  <el-option
                    v-for="item in vendorOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 变体 -->
        <div class="myCard" style="margin-bottom:20px;">
          <p class="myCardTitle flex">
            <span>Variants</span>
          </p>
          <el-radio-group v-model="formData.type" :disabled="true">
            <el-radio :label="0">Simple product</el-radio>
            <el-radio :label="1">Variants</el-radio>
          </el-radio-group>
          <div
            v-if="formData.type === 1"
            style="margin-top: 15px;padding-top:15px;border-top: 1px solid #ddd; width: 100%;"
          >
            <!-- 规格信息 -->
            <el-row :gutter="20">
              <div v-for="(item, index) in specifications" :key="index">
                <el-col :span="6">
                  <el-form-item label="" label-width="100px">
                    {{ item.name }}
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label-width="10px">
                    <el-tag
                      v-for="(it, i) in item.children"
                      :key="i"
                      class="variantValues"
                    >{{ it }}</el-tag>
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
            <!-- 变种信息 -->
            <div class="specificationData">
              <div v-if="formData.specificationData.length" class="batchEditor">
                <span>Batch operation: </span>
                <div class="titles">
                  <template v-for="(item, index) in batchOptions">
                    <template v-if="item.type === 'input'">
                      <el-button
                        :key="index"
                        size="mini"
                        @click="setInputVal(item.label)"
                      >{{ item.title }}</el-button>
                    </template>
                    <template v-if="item.type === 'checkbox'">
                      <el-button :key="index" size="mini">
                        {{ item.title }}
                        <el-checkbox
                          :true-label="1"
                          :false-label="0"
                          @change="
                            (checked) => batchCheckChange(checked, item.label)
                          "
                        />
                      </el-button>
                    </template>
                  </template>
                </div>
              </div>
              <div
                v-for="(item, index) in formData.specificationData"
                :key="index"
                class="specificationBox"
              >
                <div class="specLeft">
                  <p>Image</p>
                  <el-image
                    v-if="item.thumbnailUri"
                    :src="
                      item.thumbnailUri.indexOf('http') === 0
                        ? item.thumbnailUri
                        : imgPrefix + item.thumbnailUri + imgSuffix
                    "
                    @click="
                      toProview(
                        item.thumbnailUri.indexOf('http') === 0
                          ? item.thumbnailUri
                          : imgPrefix + item.thumbnailUri
                      )
                    "
                  />
                  <i
                    v-else
                    class="el-icon-plus uploader-icon"
                    @click="showVariantImgDialog(index, null, null)"
                  />
                </div>
                <div class="specCenter">
                  <el-table ref="multipleTable" :data="[item]">
                    <el-table-column prop="salePrice" label="Sale Price($)">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'specificationData.' + index + '.salePrice'"
                          :rules="formData.rules.salePrice"
                        >
                          <el-input v-model="scope.row.salePrice" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="regularPrice"
                      label="Regular Pricee($)"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'specificationData.' + index + '.regularPrice'"
                          :rules="formData.rules.regularPrice"
                        >
                          <el-input v-model="scope.row.regularPrice" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="saleTime" label="Sale Time">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'specificationData.' + index + '.saleTime'"
                          :rules="formData.rules.saleTime"
                        >
                          <el-date-picker
                            v-model="scope.row.saleTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="timeChange"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="offSaleTime" label="OffSale Time">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'specificationData.' + index + '.offSaleTime'"
                          :rules="formData.rules.offSaleTime"
                        >
                          <el-date-picker
                            v-model="scope.row.offSaleTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="timeChange"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="Tax status">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.taxStatus">
                          <el-option label="None" :value="0" />
                          <el-option label="Taxable" :value="1" />
                          <el-option label="Shipping only" :value="2" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="Tax class">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.taxClass">
                          <el-option label="Standard" value="Standard" />
                          <el-option
                            label="Reduced rate"
                            value="Reduced rate"
                          />
                          <el-option label="Zero rate" value="Zero rate" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="variantSku"
                      label="Variant sku"
                      width="100"
                    />
                    <el-table-column prop="Bar code" label="Bar Code">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'specificationData.' + index + '.barcode'"
                          :rules="formData.rules.barcode"
                        >
                          <el-input v-model="scope.row.barcode" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-table ref="multipleTable" :data="[item]">
                    <el-table-column label="Virtual" width="80px">
                      <template slot-scope="scope">
                        <el-checkbox
                          v-model="scope.row.isVirtual"
                          :true-label="1"
                          :false-label="0"
                          @change="
                            (val) => specToggleCheck(val, 'isVirtual', index)
                          "
                        />
                      </template>
                    </el-table-column>
                    <template v-if="item.isVirtual === 0">
                      <el-table-column label="Weight(kg)">
                        <template slot-scope="scope">
                          <el-form-item
                            :prop="'specificationData.' + index + '.weight'"
                            :rules="formData.rules.weight"
                          >
                            <el-input v-model="scope.row.weight" />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="Length(cm)">
                        <template slot-scope="scope">
                          <el-form-item
                            :prop="'specificationData.' + index + '.length'"
                            :rules="formData.rules.length"
                          >
                            <el-input v-model="scope.row.length" />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="Width(cm)">
                        <template slot-scope="scope">
                          <el-form-item
                            :prop="'specificationData.' + index + '.width'"
                            :rules="formData.rules.width"
                          >
                            <el-input v-model="scope.row.width" />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="Height(cm)">
                        <template slot-scope="scope">
                          <el-form-item
                            :prop="'specificationData.' + index + '.height'"
                            :rules="formData.rules.height"
                          >
                            <el-input v-model="scope.row.height" />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="Shipping class">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.shippingClassId">
                            <el-option label="No shipping class" :value="0" />
                          </el-select>
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column label="Stock" width="80px">
                      <template slot-scope="scope">
                        <el-checkbox
                          v-model="scope.row.isManage"
                          :true-label="1"
                          :false-label="0"
                          @change="
                            (val) => specToggleCheck(val, 'isManage', index)
                          "
                        />
                      </template>
                    </el-table-column>
                    <template v-if="item.isManage">
                      <el-table-column label="Quantity">
                        <template v-if="scope.row.isManage" slot-scope="scope">
                          <el-form-item
                            :prop="'specificationData.' + index + '.quantity'"
                            :rules="formData.rules.quantity"
                          >
                            <el-input v-model.number="scope.row.quantity" />
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column label="Allow backorders">
                        <template v-if="scope.row.isManage" slot-scope="scope">
                          <el-checkbox
                            v-model="scope.row.allowBackorders"
                            :true-label="1"
                            :false-label="0"
                            @change="
                              (val) =>
                                specToggleCheck(val, 'allowBackorders', index)
                            "
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        v-if="item.isManage == 1 && item.allowBackorders === 1"
                        label="LowInventory threshold"
                      >
                        <template slot-scope="scope">
                          <el-form-item
                            :prop="
                              'specificationData.' +
                                index +
                                '.lowInventoryThreshold'
                            "
                            :rules="formData.rules.lowInventoryThreshold"
                          >
                            <el-input
                              v-model.number="scope.row.lowInventoryThreshold"
                            />
                          </el-form-item>
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column v-else label="status">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.status">
                          <el-option label="In stock" :value="0" />
                          <el-option label="Out of stock" :value="1" />
                          <el-option label="On backOrder" :value="2" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="Sold individually">
                      <template slot-scope="scope">
                        <el-checkbox
                          v-model="scope.row.isSoldIndividually"
                          :true-label="1"
                          :false-label="0"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </template>

    <!-- 数据请求时显示loading -->
    <div
      v-else
      v-loading="loading"
      element-loading-text="loading..."
      style="height: 120px;"
    />

    <div :class="[{ open: $store.state.app.sidebar.opened }, 'bottomBtns']">
      <div class="right">
        <el-button type="primary" :disabled="true">Issue</el-button>
        <el-button
          type="primary"
          :disabled="loading || !storeId"
          @click="submitData"
        >Save</el-button>
        <el-button @click="goBack()">Back</el-button>
      </div>
    </div>

    <!-- 查看全部标签 -->
    <all-tag
      v-if="viewTags"
      :selected-id="formData['productTagIds']"
      :store-id="storeId"
      :view-tags="viewTags"
      @closeTagsDialog="closeTagsDialog"
      @getSelectedTag="getSelectedTag"
      @setTagList="setTagList"
    />

    <!-- 查看全部分类 -->
    <multiple-category
      v-if="viewCategory"
      :store-id="storeId"
      :view-category="viewCategory"
      @closeCategoryDialog="closeCategoryDialog"
      @getSelectedCategory="getSelectedCategory"
      @setCategoryList="setCategoryList"
    />

    <!-- 查看全部供应商 -->
    <all-vendor
      v-if="viewVendor"
      :selected-id="formData['vendorId']"
      :store-id="storeId"
      :view-vendor="viewVendor"
      @closeVendorDialog="closeVendorDialog"
      @getSelectedVendor="getSelectedVendor"
      @setVendorList="setVendorList"
    />

    <!-- 批量修改弹窗 -->
    <batch-modify
      v-if="batchVisible"
      :label="writeLabel"
      @closeBatch="closeBatch"
    />

    <!-- 图片预览 -->
    <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />
  </div>
</template>

<script>
import { authorizedList } from '@/api/authorized';
import {
  productWoocRead,
  productWoocEdit,
  productCategoryList,
  productCategoryAdd,
  productTagList,
  productTagAdd,
  vendorList,
  vendorAdd
} from '@/api/product';
import UE from '@/components/Ueditor/ueditor.vue';
import AllTag from '../components/allTag';
import MultipleCategory from '../components/multipleCategory';
import AllVendor from '../components/allVendor';
import BatchModify from '../components/batchModify';
import ProviewImg from '@/components/Proview/proviewImg';
import { flatten } from '@/utils/dataFormat';
import {
  formRules,
  batchOption,
  toggleCheck,
  changeVariantSku
} from '../pageScript/commonDet';
export default {
  components: {
    UE,
    AllTag,
    MultipleCategory,
    AllVendor,
    BatchModify,
    ProviewImg
  },
  data() {
    return {
      loading: true,
      storeId: null, // 店铺ID
      productId: null, // 商品ID
      storeList: [],
      categoryOptions: [], // 分类列表
      categoryProp: {
        multiple: true,
        checkStrictly: true,
        emitPath: false,
        label: 'name',
        value: 'id',
        children: 'seconds'
      },
      category: [],
      tagOptions: [],
      vendorOptions: [],
      formData: {
        isManageInventory: 0,
        inventoryStatus: 0,
        taxStatus: 1,
        taxClass: 'Standard',
        type: 0,
        isVirtual: 0,
        shippingClassId: 0,
        productTagIds: [],
        isDimensions: 0,
        // 生成的变种信息
        specificationData: []
      },
      rules: formRules(this.checkStr, this),
      ue: 'ue',
      defaultMsg: '',
      images: [],
      proviewUrl: '', // 预览图片Url
      timeChange: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 选择时间范围
        }
      },
      viewTags: false,
      viewCategory: false,
      viewVendor: false,
      viewVariant: false,
      chargeTax: '',
      allListLeaf: [], // 所有规格叶子节点，比对规格ID使用
      specifications: [], // 规格信息(树结构)
      firstRandom: true, // 首次渲染变种信息
      cloneSpecificationData: [], // 商品中保存的规格信息，新加规格信息若在其中存在，使用其数据
      specList: [],
      selectOptions: [], // 当前选取规格值得子选项
      batchVisible: false,
      writeLabel: '', // 批量写入变种信息的具体参数
      batchRows: [],
      variantDialogVisible: false,
      batchOptions: batchOption
    };
  },
  mounted() {
    this.$set(this.formData, 'rules', this.rules);
    if (this.$route.params.storeId) {
      this.storeId = Number(this.$route.params.storeId);
      this.productId = this.$route.params.productId;
      this.getStoreList();
      this.vendorList(true);
      this.productCategoryList(true);
      this.productTagList(true);
      this.chosedStore(this.storeId);
    } else {
      // 草稿箱编辑
      this.productId = Number(this.$route.params.productId);
      this.getStoreList(true);
    }
  },
  methods: {
    async getStoreList(boolean) {
      // 获取店铺列表
      const res = await authorizedList({
        storeType: 'WOOCOMMERCE'
      });
      this.storeList = res.data;
      if (boolean && res.data.length > 0) {
        this.storeId = res.data[0].id;
        this.chosedStore();
      }
      if (boolean && res.data.length === 0) {
        const h = this.$createElement;
        this.$notify.error({
          title: 'Error',
          message: h('p', null, [
            h(
              'span',
              null,
              'You do not have an authorized shop, please go to '
            ),
            h(
              'el-button',
              {
                attrs: { type: 'text' },
                on: {
                  click: this.goStorePage
                }
              },
              'Add'
            ),
            h('span', null, ' authorization first')
          ]),
          duration: 0
        });
        this.productRead();
      }
    },
    goStorePage() {
      this.$router.push('/store/wooc');
    },
    chosedStore() {
      this.vendorList(true);
      this.productCategoryList(true);
      this.productTagList(true);
      this.productRead();
    },
    productRead() {
      productWoocRead(this.productId).then((res) => {
        const data = JSON.parse(JSON.stringify(res.data));
        // 价格/100
        if (data.product.type === 1) {
          data.inventories.forEach((item) => {
            item.salePrice /= 100;
            item.regularPrice /= 100;
          });
        }
        data.product.regularPrice /= 100;
        data.product.salePrice /= 100;
        this.formData = data.product;

        this.defaultMsg = data.content.description;

        this.$set(
          this.formData,
          'productCategoryIds',
          this.$route.params.storeId
            ? data.product.categoryIds.split(',').map((item) => Number(item))
            : []
        );
        this.$set(
          this.formData,
          'productTagIds',
          this.$route.params.storeId
            ? data.product.tagIds.split(',').map((item) => Number(item))
            : []
        );
        this.$set(this.formData, 'specificationData', data.inventories);
        this.images = data.images || [];
        this.$set(this.formData, 'rules', this.rules);
        if (!this.$route.params.storeId) {
          this.$set(this.formData, 'vendorId', null);
        }
        if (data.product.type === 1) {
          this.cloneSpecificationData = JSON.parse(
            JSON.stringify(data.inventories)
          );
          var allTitleValues = [];
          data.inventories.forEach((item, index) => {
            allTitleValues.push(item.titleValues.split(','));
          });
          // 解析转换 规格信息 数据
          const arr = data.inventories.map((item) => {
            return item.titleValues.split('_');
          });
          data.variants.forEach((item, index) => {
            item.children = [];
            arr.forEach((it) => {
              if (!item.children.includes(it[index])) {
                item.children.push(it[index]);
              }
            });
          });
          this.specifications = data.variants;
        } else if (data.product.type === 0) {
          this.formData['productVariantIds'] = [];
        }
        this.loading = false;
      });
    },
    productCategoryList(val) {
      // 获取分类
      if (val) {
        productCategoryList({ storeId: this.storeId, parentId: -1 }).then(
          (res) => {
            const arr = [];
            res.data.forEach((item, index) => {
              arr[index] = item.first;
              arr[index]['seconds'] = item.seconds;
            });
            this.categoryOptions = arr;
          }
        );
      }
    },
    categoryChange(val) {
      // 添加分类
      const value = val[val.length - 1];
      if (typeof value === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: value,
          storeId: this.storeId
        };
        productCategoryAdd(params).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message);
            productCategoryList({ storeId: this.storeId, parentId: -1 }).then(
              (res) => {
                if (res.code === 200) {
                  const arr = [];
                  res.data.forEach((item, index) => {
                    arr[index] = item.first;
                    arr[index]['seconds'] = item.seconds;
                  });
                  this.categoryOptions = arr;
                  const id = res.data.filter((item) => item.name === value)[0]
                    .id;
                  this.formData.productCategoryIds[
                    this.formData.productCategoryIds.length - 1
                  ] = id;
                }
              }
            );
          } else {
            this.formData.productCategoryIds.splice(val.length - 1, 1);
          }
        });
      }
    },
    productTagList(val) {
      // 标签列表
      if (val) {
        productTagList(this.storeId).then((res) => {
          this.tagOptions = res.data;
        });
      }
    },
    productTagAdd(val) {
      // 添加标签
      const value = val[val.length - 1];
      if (typeof value === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: value,
          storeId: this.storeId
        };
        productTagAdd(params).then((res) => {
          if (res.code === 200) {
            productTagList(this.storeId).then((res) => {
              if (res.code === 200) {
                this.tagOptions = res.data;
                const id = res.data.filter((item) => item.name === value)[0].id;
                this.formData.productTagIds[
                  this.formData.productTagIds.length - 1
                ] = id;
              }
            });
          } else {
            this.formData.productTagIds.splice(val.length - 1, 1);
          }
        });
      }
    },
    getClick(e, str) {
      if (e.target.tagName === 'SPAN' && e.target.className === '') {
        switch (str) {
          case 'vendor':
            this.viewVendor = true;
            break;
          case 'tag':
            this.viewTags = true;
            break;
          case 'category':
            this.viewCategory = true;
            break;
        }
      }
    },
    vendorList(val) {
      if (val) {
        vendorList().then((res) => {
          this.vendorOptions = res.data;
        });
      }
    },
    vendorAdd(val) {
      // 添加标签
      if (typeof val === 'string') {
        const params = {
          name: val,
          storeId: this.storeId
        };
        vendorAdd(params).then((res) => {
          if (res.code !== 200) {
            this.formData.vendorId = '';
          } else {
            this.vendorList(true);
          }
        });
      }
    },
    productWoocEdit(params) {
      productWoocEdit(params).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$router.go(-1);
        }
      });
    },
    submitData() {
      this.$refs['productForm'].validate((valid) => {
        if (valid) {
          // 校验商品缩略图
          if (this.images.length === 0) {
            const offsetTop = document.getElementById('Images').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please Add/Select the images');
            return;
          }
          const params = JSON.parse(JSON.stringify(this.formData));
          params['storeId'] = this.storeId;
          params['inventories'] = JSON.parse(
            JSON.stringify(this.formData.specificationData)
          );
          params.content = {};
          params.content['description'] = this.$refs.ue.getUEContent();
          // 校验商品描述
          if (params.content['description'] === '') {
            const offsetTop = document.getElementById('Description').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please fill in the description');
            return;
          }
          params['productImageIds'] = this.images.map((item) => item.id);
          params['productCategoryIds'] = flatten(params['productCategoryIds']);
          if (typeof params.vendorId === 'string') {
            // 提交数据时供应商为新加的时，匹配下对应id
            params.vendorId = this.vendorOptions.filter(
              (item) => item.name === params.vendorId
            )[0].id;
          }
          // 价格*100
          if (params.type === 1) {
            if (params.inventories.length === 0) {
              return this.$message.warning('Please add variant information');
            }
            params.inventories.forEach((item) => {
              item.salePrice = Math.round(item.salePrice * 100);
              item.regularPrice = Math.round(item.regularPrice * 100);
              item.quantity *= 1;
            });
            params.productVariantIds = params.variantIds
              .split(',')
              .map((item) => ~~item);
          } else if (params.type === 0) {
            params.inventories = [];
            params.productVariantIds = [];
          }
          params.regularPrice = Math.round(params.regularPrice * 100);
          params.salePrice = Math.round(params.salePrice * 100);
          params.inventoryQuantity *= 1;

          params.productGroupIds = [];
          this.productWoocEdit(params);
        } else {
          this.$message.warning('Please complete the information');
          return false;
        }
      });
    },
    changeVariantSku(val) {
      changeVariantSku(val, this);
    },
    toggleCheck(val, label) {
      // 取消勾选表单复选框，清空对应数据
      toggleCheck(val, label, this);
    },
    specToggleCheck(val, label, index) {
      // 取消勾选变种内表单复选框，清空对应数据
      if (val === 0) {
        if (label === 'isManage') {
          this.formData.specificationData[index]['quantity'] = 0;
          this.formData.specificationData[index]['allowBackorders'] = 0;
          this.formData.specificationData[index]['lowInventoryThreshold'] = 0;
        } else if (label === 'allowBackorders') {
          this.formData.specificationData[index]['lowInventoryThreshold'] = 0;
        }
      } else {
        if (label === 'isVirtual') {
          delete this.formData.specificationData[index]['weight'];
          delete this.formData.specificationData[index]['length'];
          delete this.formData.specificationData[index]['width'];
          delete this.formData.specificationData[index]['height'];
        }
      }
    },
    setTagList(data) {
      this.tagOptions = data;
    },
    closeTagsDialog() {
      this.viewTags = false;
    },
    getSelectedTag(data) {
      this.viewTags = false;
      this.formData.productTagIds = data;
    },
    setCategoryList(data) {
      this.categoryOptions = data;
    },
    closeCategoryDialog() {
      this.viewCategory = false;
    },
    getSelectedCategory(data) {
      this.viewCategory = false;
      this.formData.productCategoryIds = data;
    },
    setVendorList(data) {
      this.vendorOptions = data;
    },
    closeVendorDialog() {
      this.viewVendor = false;
    },
    getSelectedVendor(data) {
      this.viewVendor = false;
      this.$set(this.formData, 'vendorId', data);
    },
    closeVariantDialog() {
      // 关闭变种弹窗
      this.viewVariant = false;
    },
    emitClose(data) {
      if (data[1] !== undefined) {
        if (data[0] !== this.selectedId) {
          this.formData.specificationData[this.variantIndex].thumbnailUri =
            data[1];
          this.formData.specificationData[this.variantIndex].imageId = data[0];
        }
      }
      this.variantDialogVisible = false;
    },
    removeItem(index) {
      this.specifications.splice(index, 1);
    },
    batchData() {
      this.batchRows = this.formData.specificationData;
      this.batchVisible = true;
    },
    closeBatch(data) {
      this.batchVisible = false;
      if (data) {
        this.formData.specificationData.forEach((item) => {
          this.$set(item, this.writeLabel, data);
        });
      }
    },
    setInputVal(label) {
      // 批量设置变种信息
      if (this.formData.specificationData.length === 0) {
        return this.$message.warning('Please add the variant first');
      }
      this.writeLabel = label;
      this.batchVisible = true;
    },
    batchCheckChange(val, label) {
      // 批量设置变种信息内复选框
      if (this.formData.specificationData.length === 0) {
        return this.$message.warning('Please add the variant first');
      }
      this.formData.specificationData.forEach((item) => {
        item[label] = val;
        if (label === 'isVirtual' && val === 1) {
          delete item['weight'];
          delete item['length'];
          delete item['width'];
          delete item['height'];
        } else if (label === 'isManage' && val === 0) {
          item['lowInventoryThreshold'] = 0;
          delete item['quantity'];
          delete item['lowInventoryThreshold'];
        } else if (label === 'allowBackorders' && val === 0) {
          delete ['lowInventoryThreshold'];
        }
      });
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    goBack() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
.app-container {
  background-color: #fbfbfb;
}
.el-table {
  margin-bottom: 0;
}
.pageTitle {
  font-size: 22px;
  padding: 10px 0 20px;
}
.noDataTip {
  font-size: 12px;
  text-align: center;
  color: #848484;
}
::v-deep .el-form--label-top .el-form-item__label {
  padding-bottom: 5px;
}
.myCard {
  box-shadow: 0 0 0 1px #ddd;
  padding: 15px;
  background: #fff;
  margin-bottom: 20px;
  border-radius: 6px;
  width: 100%;
  .myCardTitle {
    font-weight: 600;
    padding-bottom: 15px;
    &.flex {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    > span {
      font-weight: 600;
    }
  }
  .variantValues {
    margin-right: 5px;
  }
  ::v-deep label {
    font-weight: 500;
  }
  .storeItem {
    margin-bottom: 0;
    ::v-deep .el-form-item__label {
      padding-bottom: 0;
      width: 120px;
    }
    ::v-deep .el-form-item__content {
      display: inline-block;
    }
  }
  .flexCol {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 32px;
    margin-bottom: 18px;
    > .el-form-item {
      margin-bottom: 0;
      margin-left: 20px;
    }
  }
  .w100 {
    width: 100%;
  }
}
.productInfo {
  display: flex;
  ::v-deep .el-form-item__label {
    width: 100%;
    .customLabel {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
  .infoLeft {
    flex: 4;
    width: 0;
    margin-right: 20px;
    ::v-deep #editor {
      line-height: normal;
    }
  }
  .infoRight {
    flex: 1;
    .el-select,
    .el-date-editor,
    .el-cascader {
      width: 100%;
      min-width: 200px;
    }
  }
}

.batchEditor {
  display: flex;
  align-items: center;
  > span {
    margin-right: 15px;
  }
  .titles {
    flex: 1;
    overflow-x: scroll;
    white-space: nowrap;
    padding: 10px 0;
    .el-button {
      padding: 5px 11px;
    }
  }
}
.specificationBox {
  display: flex;
  border-bottom: 10px solid rgba(0, 0, 0, 0.1);
  padding-bottom: 15px;
  .specLeft {
    width: 150px;
    p {
      color: #000;
      font-size: 13px;
      font-weight: bold;
      line-height: 23px;
      padding: 8px 0;
    }
    .el-image {
      width: 139px;
      height: 139px;
      cursor: pointer;
    }
    i {
      font-size: 16px;
      color: #8c939d;
      width: 139px;
      height: 139px;
      line-height: 139px;
      text-align: center;
      border: 1px dotted #ddd;
      cursor: pointer;
    }
  }
  .specCenter {
    width: 0;
    flex: 1;
    ::v-deep .el-table__body-wrapper {
      overflow: unset;
      table {
        td {
          .cell {
            overflow: unset;
            padding-bottom: 8px;
            .el-date-editor {
              width: 100%;
            }
            .el-form-item {
              margin-bottom: 0;
            }
          }
        }
      }
    }
  }
}
.bottomBtns {
  position: fixed;
  bottom: 0px;
  right: 0px;
  box-sizing: border-box;
  width: calc(100% - 54px);
  background: #fff;
  padding: 10px 20px;
  border-top: 1px solid #ccc;
  transition: width 0.28s;
  z-index: 145;
  &.open {
    width: calc(100% - #{$sideBarWidth});
  }
  .right {
    text-align: right;
  }
}
</style>
